package org.mineground.commands.irc;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import org.jibble.pircbot.Colors;
import org.jibble.pircbot.User;
import org.mineground.Main;
import org.mineground.Utilities;
import org.mineground.handlers.IPBanHandler;
import org.mineground.handlers.irc.CommandExecutor;
import org.mineground.handlers.irc.UserLevel;

/**
 * @name IPInfo.java
 * @author Daniel Koenen (2012)
 */
public class IPInfo implements CommandExecutor {
    @Override
    public void onCommand(User sender, UserLevel level, String channel, String command, String arguments[]) {
	if (level.compareTo(UserLevel.IRC_OP) < 0) {
	    return;
        }

        if (arguments.length < 1) {
            Main.getInstance().getIRCHandler().sendMessage(channel, Colors.RED + "* Usage:" + Colors.NORMAL + " !ipinfo [name/ip-address/range]");
	    return;
	}
        
        String searchIndex = arguments[0];
        
        if (searchIndex.matches("(\\d{1,3}|\\*)\\.(\\d{1,3}|\\*)\\.(\\d{1,3}|\\*)\\.(\\d{1,3}|\\*)")) {
            searchIP(searchIndex, channel);
            return;
        }
        
        searchName(searchIndex, channel);
    }
    
    private void searchIP(String ipAddress, String channelName) {
        try {
            long rangeStart = IPBanHandler.getRangeStart(ipAddress);
            long rangeEnd = IPBanHandler.getRangeEnd(ipAddress);
            
            PreparedStatement queryStatement = Main.getInstance().getDatabaseHandler().getConnection().prepareStatement("SELECT login_name, COUNT(*) FROM lvm_player_joins WHERE ip_address >= ? AND ip_address <= ? GROUP BY login_name ORDER BY join_date DESC");
            queryStatement.setLong(1, rangeStart);
            queryStatement.setLong(2, rangeEnd);
            queryStatement.execute();
            
            ResultSet queryResult = queryStatement.getResultSet();
            
            StringBuilder outputBuilder = new StringBuilder();
            outputBuilder.append(Colors.TEAL);
            outputBuilder.append("* Names from IP \"");
            outputBuilder.append(ipAddress);
            outputBuilder.append("\"");
            outputBuilder.append(Colors.NORMAL);
            outputBuilder.append(": ");
            
            short playerIndex = 0;
            while(queryResult.next()) {
                if (playerIndex < 10) {
                    outputBuilder.append(queryResult.getString(1));
                    outputBuilder.append(Colors.DARK_GRAY);
                    outputBuilder.append(" (x");
                    outputBuilder.append(queryResult.getInt(2));
                    outputBuilder.append(")");
                    outputBuilder.append(Colors.NORMAL);
                    outputBuilder.append(", ");
                }
                
                playerIndex++;
            }
            
            String output = outputBuilder.substring(0, outputBuilder.length() - 2);
            
            if (playerIndex > 10) {
                output += " (and " + (playerIndex - 10) + " more)";
            }
            
            if (playerIndex > 0) {
                Main.getInstance().getIRCHandler().sendMessage(channelName, output);
                return;
            }
            
            Main.getInstance().getIRCHandler().sendMessage(channelName, Colors.TEAL + "* No results found.");
            queryStatement.close();
        }
        
        catch (Exception exception) {
            exception.printStackTrace();
        }
    }
    
    private void searchName(String playerName, String channelName) {
        try {
            PreparedStatement queryStatement = Main.getInstance().getDatabaseHandler().getConnection().prepareStatement("SELECT ip_address, country_code FROM lvm_player_joins WHERE login_name = ? GROUP BY ip_address ORDER BY join_date DESC");
            queryStatement.setString(1, playerName);
            queryStatement.execute();
            
            ResultSet queryResult = queryStatement.getResultSet();
            
            StringBuilder outputBuilder = new StringBuilder();
            outputBuilder.append(Colors.TEAL);
            outputBuilder.append("* IPs from name \"");
            outputBuilder.append(playerName);
            outputBuilder.append("\"");
            outputBuilder.append(Colors.NORMAL);
            outputBuilder.append(": ");
            
            short addressIndex = 0;
            while(queryResult.next()) {
                if (addressIndex < 10) {
                    outputBuilder.append(Utilities.longToIp(queryResult.getLong(1)));
                    outputBuilder.append(Colors.DARK_GRAY);
                    outputBuilder.append(" (");
                    outputBuilder.append(queryResult.getString(2));
                    outputBuilder.append(")");
                    outputBuilder.append(Colors.NORMAL);
                    outputBuilder.append(", ");
                }
                
                addressIndex++;
            }
            
            String output = outputBuilder.substring(0, outputBuilder.length() - 2);
            
            if (addressIndex > 10) {
                output += " (and " + (addressIndex - 10) + " more)";
            }
            
            if (addressIndex > 0) {
                Main.getInstance().getIRCHandler().sendMessage(channelName, output);
                return;
            }
            
            Main.getInstance().getIRCHandler().sendMessage(channelName, Colors.TEAL + "* No results found.");
            queryStatement.close();
        }
        
        catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}
